package org.example.day05;

/**
 * 第二章节2.2.12: 多线程的死锁 (A线程持有锁不释放，B线程无法获取锁，就会造成B线程的死锁)
 */
public class MyThread10 implements Runnable{
    public String username;
    public Object lock1 = new Object();
    public Object lock2 = new Object();
    public void setFlag(String username){
        this.username = username;
    }
    @Override
    public void run() {
        if(username.equals("a")){
            synchronized (lock1){
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println("按 lock1 --> lock2 代码顺序执行了");
                }
            }
        }
        if(username.equals("b")){
            synchronized (lock2){
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println("按 lock2 --> lock1 代码顺序执行了");
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            MyThread10 m10 = new MyThread10();
            m10.setFlag("a");
            Thread t1 = new Thread(m10);
            t1.start();
            Thread.sleep(100);
            m10.setFlag("b");
            Thread t2 = new Thread(m10);
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
